<?php


namespace app\common\controller;


use app\BaseController;
use app\common\middleware\BeComplicatedBy;
use app\common\middleware\Token;
use think\event\LogWrite;
use think\facade\Event;

/**
 * Class Api 接口基类
 * @package app\common\controller
 */
class Api extends BaseController
{
    /**
     * @var array|string[] 控制器中间件
     */
    public $middleware = [Token::class, BeComplicatedBy::class ];

    /**
     * 初始化函数
     */
    protected function initialize()
    {
        Event::listen(LogWrite::class, function ($event) {
            $this->requestListen($event);
        });
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 验证数据并返回数据
     * @param string $scene 场景值或验证器带场景值
     * @example $this->validateGetData('add') | $this->validateGetData('\\app\\common\\validate\\User.add')
     * @return array
     */
    final public function validateGetData(string $scene)
    {
        $data = $this->request->post();

        if (strpos($scene, '\\') !== false) {
            $validateAndScene = $scene;
            list($validate, $scene) = explode('.', $validateAndScene);
        }else{
            $validateClass = explode('\\', static::class);
            $validateClass = array_pop($validateClass);
            $validate = "\\app\\common\\validate\\{$validateClass}";
            $validateAndScene = "{$validate}.{$scene}";
        }

        $this->validate($data, $validateAndScene);

        $validateField = get_class_attr($validate, 'scene', [])[$scene] ?? [];

        return data_only($data, $validateField);
    }


    /**
     * 请求监听
     * @param LogWrite $event
     */
    private function requestListen(LogWrite $event)
    {
        if ($this->request->middleware('request_listen') !== true) {
            unset($event->log['info'], $event->log['sql']);
            return;
        }

        $info = $sql = [];
        $end = '';
        foreach ($event->log as $key => $value) {
            if ($key === 'info') {
                $end = array_pop($value);
                $info = $value;
            } else if($key === 'sql') {
                $sql = $event->log['sql'];
            }
        }
        $event->log['sql'] = [];
        $event->log['info'] = ["\r\n" . implode("\r\n > ", array_merge($info, $sql)) . "\r\n" .  $end];
    }
}

